import sys,os,json,subprocess
#sys.path.append('F:\QL_tool_file')
from PyQt6.QtWidgets import QApplication, QWidget, QSystemTrayIcon, QMenu, QMessageBox,QWidgetAction,QHBoxLayout,QPushButton,QLabel,QStyle
from PyQt6.QtGui import QIcon, QAction
#from main import MainWindow, SoftwareSet
from PyQt6.QtCore import QFile, QTextStream

#from Window_Tool.LogicalFile.Storyboard.untitled_ui import Ui_MainWindow
ARGV = sys.argv
#DEBUGMODE = len(ARGV) > 1 and ARGV[1] == '-debug'
class MyWindow(QWidget):
    def __init__(self):
        super().__init__()
        
        self.initUI()
    def initUI(self):
        # 创建托盘图标
        self.tray_icon = QSystemTrayIcon(QIcon('{}/公众号.png'.format(os.path.dirname(__file__))), self)
        self.tray_icon.setToolTip(u'灵屿工具')
        self.tray_menu = TrayMenu(self)
        self.tray_icon.setContextMenu(self.tray_menu)
        # 连接托盘图标的双击和右键菜单激活事件
        self.tray_icon.activated.connect(self.overlay_activated)
    def main(self):
        # 显示托盘图标
        self.tray_icon.show()
        # 显示托盘图标的消息提示
        self.tray_icon.showMessage(u"灵屿工具", u'启动成功', icon=QSystemTrayIcon.MessageIcon.Information)
    def overlay_activated(self, reason):
        # 处理托盘图标的双击和右键菜单激活事件
        if reason == QSystemTrayIcon.ActivationReason.Trigger:
            pass
        elif reason == QSystemTrayIcon.ActivationReason.Context:
            self.tray_menu.clear()
            self.tray_menu.build_menu()
        elif reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            pass
        elif reason == QSystemTrayIcon.ActivationReason.MiddleClick:
            pass
        '''
        elif reason == QSystemTrayIcon.ActivationReason.DoubleClick:
            self.toggleVisibility()
        elif reason == QSystemTrayIcon.ActivationReason.Context:
            pass
        '''
class TrayMenu(QMenu):
    def __init__(self,parent_obj):
        super().__init__()
        self.parent_obj = parent_obj
        self.TD_path = os.path.dirname(__file__).replace('\\', '/').rsplit('/', 2)[0]
        self.json_path = '{}/SysTray.json'.format(os.path.dirname(__file__))
        #print(self.json_path)
        self.build_menu()

    def recursive(self, item_list, parent):
        u"""
        构建菜单的递归函数
        :param item_list: 创建列表
        :param parent: 父物体
        """
        for i in item_list:
            if i['type'] == 'menu':
                menu = QMenu(parent)
                menu.setTitle(i['label'])
                if 'icon' in i.keys():
                    menu.setIcon(QIcon(i['icon']))
                    print(i['label'])
                parent.addMenu(menu)
                self.recursive(i['children'], menu)
            elif i['type'] == 'action':
                exit_action = QAction(i['label'], self)
                self.build_action(exit_action, i)
                parent.addAction(exit_action)

    def build_action(self, action, i):
        command = i['command']
        RootDirectory = os.path.dirname(os.path.dirname(__file__))
        #print(command)
        FullPath = os.path.join(RootDirectory,command).replace('\\','/')
        print(FullPath)
        action.triggered.connect(lambda *args: self.launch_program(RootDirectory,FullPath))

    def build_menu(self):
        u"""构建菜单"""
        print(self.json_path)
        with open(self.json_path, "r" ,encoding='utf8') as f:
            menu_list = json.load(f)
            print(menu_list)
        self.recursive(menu_list, self)
        # 获取当前文件的绝对路径
        self.current_file = os.path.abspath(__file__)
        # 获取当前文件所在的目录
        self.current_dir = os.path.dirname(self.current_file)
        # 构建 styles.css 的绝对路径
        #self.styles_css_path = os.path.join(self.current_dir, 'styles.css')
        self.styles_css_path = '{}/styles.css'.format(os.path.dirname(__file__))
        
        '''
        # 创建右键菜单
        menu = QMenu(self)
        menu.setTitle(u'启动器')    
        self.addMenu(menu)
        # 创建打开启动器动作，并连接到打开启动器的槽函数
        open_launcher_action = QAction(u'打开(&W)', self)
        # 连接信号和槽
        open_launcher_action.triggered.connect(lambda *args: self.launch_program())
        Desktop_launcher_action = QAction(u'添加到桌面', self)
        #Desktop_launcher_action.triggered.connect(self.openLauncher)
        menu.addAction(open_launcher_action)
        menu.addAction(Desktop_launcher_action)
        # 创建打开启动器动作，并连接到打开启动器的槽函数
        open_Cutting_Video_action = QAction('剪辑', self)
        open_Cutting_Video_action.triggered.connect(self.openCutting_Video)
        menu.addAction(open_Cutting_Video_action)
        '''
        exit_action = QAction('退出(&Q)', self)
        exit_action.triggered.connect(QApplication.instance().quit)
        self.addAction(exit_action)
        # 从外部CSS文件加载样式表
        self.loadStylesheet(self.styles_css_path, self)

    def launch_program(self,RootDirectory,command):
        #subprocess.Popen("{} {}".format('C:\Python\Python311/python.exe', command), stdout=subprocess.PIPE)
        # 使用CREATE_NO_WINDOW标志禁止显示控制台窗口，并将stdout重定向到空设备
        #subprocess.Popen(["python", command], creationflags=subprocess.CREATE_NO_WINDOW, stdout=subprocess.DEVNULL)

        subprocess.Popen([os.path.join(os.path.dirname (RootDirectory),'.venv/Scripts/python.exe'), command], creationflags=subprocess.CREATE_NO_WINDOW, stdout=subprocess.DEVNULL)

    def loadStylesheet(self, file_path, widget):
        file = QFile(file_path)
        if not file.open(QFile.OpenModeFlag.ReadOnly | QFile.OpenModeFlag.Text):
            return
        stream = QTextStream(file)
        widget.setStyleSheet(stream.readAll())
        file.close()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.main()
    sys.exit(app.exec())